package com.heima.gateway.filter;

import com.heima.gateway.properties.AllowedUrlsProperties;
import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;



@Component
@Order(-1)
@RefreshScope
@RequiredArgsConstructor
public class AuthFilter implements GlobalFilter {


    @Value("${app-gateway.allowedUrls}")
    private String allowedUrls;
    @Value("${app-gateway.allowedUrls}")
    private List<String> urls;

    private final AllowedUrlsProperties allowedUrlsConfig;
    private final StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取url
        String url = exchange.getRequest().getURI().getPath();
        //2.是否放行
        if (allowedUrlsConfig.isUrlAllowed(url)) {
            return chain.filter(exchange);
        }
        //3.不放行 判断token是否存在
        String token = exchange.getRequest().getHeaders().getFirst("token");
        //不存在
        if (token.isEmpty()) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //存在
        String userId = redisTemplate.opsForValue().get("login_user_token:" + token);
        if (userId == null) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /* @Override
     public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
         //1.获取url
         String url = exchange.getRequest().getURI().getPath();

         //2.url是否放行
         if (isUrlAllowed(url)) {
           return chain.filter(exchange);
         }
         //3.不放行 判断token是否存在
         List<String> list = exchange.getRequest().getHeaders().get("token");
         //不存在
         if (list.isEmpty()) {
             exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
             return exchange.getResponse().setComplete();
         }
         //存在
         String token = list.get(0);
         //4.解析token
         Claims claimsBody = null;
         try {
             claimsBody = AppJwtUtil.getClaimsBody(token);
         } catch (Exception e) {
             exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
             return exchange.getResponse().setComplete();
         }
         //5.判断是否过期
         int i = AppJwtUtil.verifyToken(claimsBody);
         if (i > 0) {
             exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
             return exchange.getResponse().setComplete();
         }
         //6.放行
         return chain.filter(exchange);
     }*/

    //判断是否放行
    public boolean isUrlAllowed(String url) {
        if (allowedUrls == null) {
            return true;
        }
        // 使用split方法按逗号分割字符串，结果是一个字符串数组
        String[] urls = allowedUrls.split(",");
        // 使用Arrays.asList将数组转换为List
        List<String> urlList = Arrays.asList(urls);
        System.out.println(urlList);
        for (String u : urlList) {
            if (u.equals(url)) {
                return true;
            }
        }
        return false;
    }
}
